/**
 * 战术装备状态管理
 */
import { defineStore } from 'pinia'
import type { TacticalLoadoutResponse, TacticalFilter } from '@/types/tactical'
import { getTacticalLoadouts, getTacticalMaps, getTacticalLevels } from '@/api/tactical'

interface TacticalState {
  loadouts: TacticalLoadoutResponse[]
  maps: string[]
  levels: string[]
  loading: boolean
  mapsLoading: boolean
  levelsLoading: boolean
  error: string | null
  filters: TacticalFilter
}

export const useTacticalStore = defineStore('tactical', {
  state: (): TacticalState => ({
    loadouts: [],
    maps: [],
    levels: [],
    loading: false,
    mapsLoading: false,
    levelsLoading: false,
    error: null,
    filters: {
      map_id: '',
      level: '',
      formatted: true
    }
  }),

  getters: {
    // 获取当前选中地图的装备数据
    currentMapLoadouts(state) {
      if (!state.filters.map_id) return state.loadouts
      return state.loadouts.filter(item => item.map_id === state.filters.map_id)
    },

    // 获取当前选中等级的装备数据
    currentLevelLoadouts(state) {
      // 先获取地图筛选后的数据
      const mapFilteredLoadouts = !state.filters.map_id 
        ? state.loadouts 
        : state.loadouts.filter(item => item.map_id === state.filters.map_id)
      
      // 再进行等级筛选
      if (!state.filters.level) return mapFilteredLoadouts
      return mapFilteredLoadouts.filter(item => item.level === state.filters.level)
    },

    // 获取所有装备配置的总数
    totalLoadouts(state) {
      const currentLoadouts = this.currentLevelLoadouts
      return currentLoadouts.reduce((total, item) => {
        return total + (item.data?.total_count || 0)
      }, 0)
    },

    // 获取有效装备配置数量（预算比例在合理范围内的）
    validLoadouts(state) {
      const currentLoadouts = this.currentLevelLoadouts
      return currentLoadouts.reduce((total, item) => {
        if (!item.data?.loadouts) return total
        return total + item.data.loadouts.filter(loadout => loadout.budget_ratio <= 1.05).length
      }, 0)
    },

    // 获取平均装备价值
    averageValue(state) {
      let totalValue = 0
      let count = 0

      const currentLoadouts = this.currentLevelLoadouts
      currentLoadouts.forEach(item => {
        if (item.data?.loadouts) {
          item.data.loadouts.forEach(loadout => {
            totalValue += loadout.total_cost
            count++
          })
        }
      })

      return count > 0 ? totalValue / count : 0
    }
  },

  actions: {
    /**
     * 获取战术装备列表
     */
    async fetchLoadouts() {
      this.loading = true
      this.error = null
      
      try {
        const response = await getTacticalLoadouts(this.filters)
        if (response.code === 1) {
          this.loadouts = response.data || []
        } else {
          this.error = response.msg || '获取装备数据失败'
        }
      } catch (error) {
        this.error = error instanceof Error ? error.message : '网络错误'
        console.error('获取战术装备失败:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取地图列表
     */
    async fetchMaps() {
      this.mapsLoading = true
      
      try {
        const response = await getTacticalMaps()
        if (response.code === 1) {
          this.maps = response.data || []
        }
      } catch (error) {
        console.error('获取地图列表失败:', error)
      } finally {
        this.mapsLoading = false
      }
    },

    /**
     * 获取等级列表
     */
    async fetchLevels(mapId: string) {
      this.levelsLoading = true
      
      try {
        const response = await getTacticalLevels(mapId)
        if (response.code === 1) {
          this.levels = response.data || []
        }
      } catch (error) {
        console.error('获取等级列表失败:', error)
      } finally {
        this.levelsLoading = false
      }
    },

    /**
     * 更新筛选条件
     */
    updateFilters(newFilters: Partial<TacticalFilter>) {
      this.filters = { ...this.filters, ...newFilters }
      
      // 如果地图改变，清空等级选择并重新获取等级列表
      if (newFilters.map_id !== undefined) {
        this.filters.level = ''
        this.levels = []
        if (newFilters.map_id) {
          this.fetchLevels(newFilters.map_id)
        }
      }
      
      // 重新获取装备数据
      this.fetchLoadouts()
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.filters = {
        map_id: '',
        level: '',
        formatted: true
      }
      this.levels = []
      this.fetchLoadouts()
    }
  }
})